package com.xbongbong.parent.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.saas.constant.StringConstant;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/06/08 9:51
 */
public class LinkDataUtil {
    /**
     * 获取所有关联数据的字段，准备搜索各个业务的数据
     * @param explainList
     * @return
     */
    public static Map<String, LinkInfoPojo> getLinkInfoMap(List<FieldAttrEntity> explainList) {
        Map<String, LinkInfoPojo> linkInfoMap = new HashMap<>(explainList.size());
        explainList.forEach(item->{
            if (ExplainUtil.isSubFormNoSelectProduct(item.getFieldType())) {
                List<? extends FieldAttrEntity> subExplainList = item.getSubForm().getItems();
                subExplainList.forEach(subItem->{
                    if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), subItem.getFieldType())){
                        linkInfoMap.put(item.getAttr()+ StringConstant.POINT+subItem.getAttr(), subItem.getLinkInfo());
                    }
                });
            } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), item.getFieldType())) {
                linkInfoMap.put(item.getAttr(), item.getLinkInfo());
            }
        });
        return linkInfoMap;
    }


    /**
     * 获取关联业务对应的id或者关联数据对应的id或者主键数据
     * @param value 数据
     */
    public static Object getIdByLinkBusiness(Object value) {
        if (value instanceof List || value instanceof Collection || value instanceof JSONArray) {
            // 关联业务单选的格式
            JSONArray linkSingleList = JSON.parseArray(JSON.toJSONString(value));
            for (int i = 0; i < linkSingleList.size(); i++) {
                JSONObject linkSingle = linkSingleList.getJSONObject(i);
                if (Objects.nonNull(linkSingle) && Objects.nonNull(linkSingle.get("id"))) {
                    return linkSingle.get("id").toString();
                }
            }
        } else if (value instanceof Map) {
            Map<String, Object> map = (Map) value;
            if (map.containsKey(FieldTypeEnum.DATAID.getAlias())) {
                return map.get(FieldTypeEnum.DATAID.getAlias());
            }
        } else {
            // 关联数据因为前面解析了，所以这里直接拿
            return value;
        }
        return null;
    }
}
